Page({
  data: {
    form: {
      name: '',
      idCard: '',
      phone: '',
      address: '',

      // 救助事项
      difficultyType: '',
      eventDate: '',
      expense: '',
      applyAmount: '',
      usage: '',

      // 收款信息
      bankName: '',
      bankAccount: '',

      // 上传
      idCardImage: '',
      proofImage: '',
      billsImage: ''
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

    typeOptions: ['医疗支出困难', '教育支出困难', '因灾因祸困难', '临时失业减收', '其他突发困难'],
    typeIndex: -1,

    agreed: false,
    canSubmit: false,
    errors: {},
    showErrors: false
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('服务事项加载中...')
    console.log('临时救助页面加载', options)
    
    // 页面加载完成，隐藏加载状态
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({ [`form.${field}`]: value }, () => this.validateForm())
  },

  onTypeChange(e) {
    const { value } = e.detail
    const difficultyType = this.data.typeOptions[value]
    this.setData({ typeIndex: value, 'form.difficultyType': difficultyType }, () => this.validateForm())
  },

  onDateChange(e) {
    const { value } = e.detail
    this.setData({ 'form.eventDate': value }, () => this.validateForm())
  },

  onUploadIdCard() { this.chooseAndUploadImage('idCardImage') },
  onUploadProof() { this.chooseAndUploadImage('proofImage') },
  onUploadBills() { this.chooseAndUploadImage('billsImage') },

  chooseAndUploadImage(fieldName) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        setTimeout(() => {
          this.setData({ [`form.${fieldName}`]: tempFilePath }, () => this.validateForm())
          wx.showToast({ title: '上传成功', icon: 'success' })
        }, 1000)
      },
      fail: (err) => {
        console.error('选择图片失败', err)
        wx.showToast({ title: '图片选择失败', icon: 'none' })
      }
    })
  },

  onDeclarationChange(e) {
    const agreed = e.detail.value.includes('agree')
    this.setData({ agreed }, () => this.validateForm())
  },

  validateForm() {
    const { form, agreed, showErrors } = this.data

    const requiredFields = ['name', 'idCard', 'phone', 'address', 'difficultyType', 'eventDate', 'expense', 'applyAmount', 'usage', 'bankName', 'bankAccount']
    const isBasicValid = requiredFields.every(f => form[f] && form[f].toString().trim())

    const requiredImages = ['idCardImage', 'proofImage']
    const isImagesValid = requiredImages.every(f => form[f])

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const phoneRegex = /^1[3-9]\d{9}$/
    const bankNoRegex = /^\d{10,30}$/

    const isIdCardValid = idCardRegex.test(form.idCard)
    const isPhoneValid = phoneRegex.test(form.phone)
    const isBankValid = bankNoRegex.test(form.bankAccount)

    const canSubmit = isBasicValid && isImagesValid && isIdCardValid && isPhoneValid && isBankValid && agreed

    const errors = {}
    if (showErrors) {
      const fieldNames = {
        name: '姓名', idCard: '身份证号', phone: '联系电话', address: '家庭住址',
        difficultyType: '困难类型', eventDate: '发生日期', expense: '已发生支出', applyAmount: '拟救助金额', usage: '救助用途说明',
        bankName: '开户银行', bankAccount: '银行卡号'
      }
      requiredFields.forEach(f => {
        if (!form[f] || !form[f].toString().trim()) errors[f] = `请填写${fieldNames[f]}`
      })

      if (!form.idCardImage) errors.idCardImage = '请上传身份证照片'
      if (!form.proofImage) errors.proofImage = '请上传证明材料'

      if (form.idCard && !isIdCardValid) errors.idCard = '身份证号格式不正确'
      if (form.phone && !isPhoneValid) errors.phone = '手机号格式不正确'
      if (form.bankAccount && !isBankValid) errors.bankAccount = '银行卡号格式不正确'
      if (!agreed) errors.agreed = '请勾选申请声明'
    }

    this.setData({ canSubmit, errors })
  },

  onSubmit() {
    this.setData({ showErrors: true }, () => {
      this.validateForm()
      if (!this.data.canSubmit) {
        wx.showToast({ title: '请完善申请信息', icon: 'none' })
        return
      }
      setTimeout(() => {
        wx.showModal({
          title: '申请提交成功',
          content: '您的临时救助申请已提交，我们将在7-15个工作日内完成审核，请耐心等待。',
          showCancel: false,
          confirmText: '确定',
          success: () => { wx.navigateBack({ delta: 2 }) }
        })
      }, 2000)
    })
  },

  onBack() { wx.navigateBack() },

  onShareAppMessage() {
    return { title: '临时救助申请', path: '/pages/service/civil-affairs/relief/index' }
  }
})


